﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Xml.Linq;
using Avivo.Tools.Sprite.Models;
using Microsoft.Win32;

namespace Avivo.Tools.Sprite
{
	public class SaveXmlCommand : ICommand
	{
		#region Private members
		private SpriteViewModel parent;
		#endregion

		#region Constructor
		public SaveXmlCommand(SpriteViewModel parent)
		{
			this.parent = parent;
		}
		#endregion

		#region ICommand Members
		public bool CanExecute(object parameter)
		{
			return true;
		}

		public event EventHandler CanExecuteChanged;

		public void Execute(object parameter)
		{
			SaveFileDialog dialog = new SaveFileDialog();
			dialog.DefaultExt = "*.xml";
			dialog.Filter = "Sprite data (*.xml)|*.xml";

			if (dialog.ShowDialog() == true)
			{
				SaveXml(dialog.FileName, this.parent);
			}
		}
		#endregion

		#region Protected methods
		protected void SaveXml(string path, SpriteViewModel model)
		{
			try
			{
				var doc = new XDocument();
				var root = new XElement("Sprites");

				var group = new XElement("Group",
					new XAttribute("Name", model.BaseClassName ?? string.Empty),
					new XAttribute("InputDirectory", model.InputDirectory ?? string.Empty),
					new XAttribute("OutputDirectory", model.OutputDirectory ?? string.Empty),
					new XAttribute("BuildHtml", model.BuildSampleHtml == true),
					new XAttribute("BuildCss", model.EnableCss == true));

				foreach (var sprite in model.Sprites)
				{
					var item = new XElement("Item",
						new XAttribute("Name", sprite.Name ?? string.Empty),
						new XAttribute("Content", sprite.Content ?? string.Empty),
						new XAttribute("Template", sprite.Template ?? string.Empty));

					group.Add(item);
				}

				root.Add(group);

				doc.Add(root);

				if (File.Exists(path))
				{
					File.Delete(path);
				}
				doc.Save(path);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
			}
		}
		#endregion
	}
}
